<template>
  <el-form
    :inline="options.inline"
    :model="form"
    :label-width="options.labelWidth"
    ref="formRef"
    :label-position="options.labelPosition"
    :rules="options.rules"
    :class="options.formClass">
    <el-form-item v-for="item in formItems" :prop="item.prop" :label="item.label" :rules="item.rules">
      <component :is="item.component" :size="item.size||size" :options="item.options" :disabled="item.disabled" v-model="form[item.prop]"/>
    </el-form-item>
    <component v-for="item in componentItems" :style="style" @click="submitForm" :is="item.component" :options="item.options"/>
    <slot></slot>
  </el-form>
</template>

<script setup lang="ts">

  import {ref,Ref} from 'vue'
  import {FormInstance} from "element-plus";

  export type FormItem = {
    label: string,
    prop: string,
    component: string,
    options: any
    rules?:any
  }

  export type ComponentItem = {
    component: string,
    options: any,
    style?: any,
    disabled?:boolean
  }
  export type PropsType = {
    options: {
      labelWidth: String,
      labelPosition: string,
      inline?: boolean,
      rules?: Array<any>,
      size?: string,
      formClass:string
      formItems: Array<FormItem>,
      componentItems?: Array<ComponentItem>,
      form: any,
      formRef:Ref<FormInstance>
    }
  }
  const props = defineProps<PropsType>()
  const options = props.options
  const {formItems, componentItems, form,formRef,size} = options

  const submitForm = async () => {
    let formEl = formRef?.value;
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {

        resetForm()
      }
    })
  }

  const resetForm = () => {
    let formEl = formRef.value;
    if (!formEl) return
    formEl.resetFields()
  }
</script>
